package com.hxc.common.service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.springframework.stereotype.Service;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.transport.*;

import java.io.File;
import java.io.IOException;

@Service
public class MarkDownService {
    // 解析markdown图片正则
    private static final String MARKDOWN_IMAGE_PATTERN = "(!\\[[^\\]]*\\])\\(([^\\)]+)\\)";

    // 需要克隆git到本机的路径
    /**
     E:\git\markdown
     * */
    private final String LOCAL_PATH = "E:\\git\\markdown";

    // 需要获取markdown的git链接
    /**
     * http://10.160.2.29:17004/mes-public/mes-doc.git
     * https://gitee.com/spring-in-huangxian-county/search_markdown_data.git
     * */
    private final String GIT_PATH = "http://10.160.2.29:17004/mes-public/mes-doc.git";

    // 需要获取的git分支
    /**
     * main
     * master
     * */
    private final String GIT_BRANCH = "main";

    // 需要抓取的Git内指定文件夹的markdown
    /**
     * 5.异常SOP
     * data
     * */
    private final String MARK_DOWN_PATH = "05.异常SOP";

    // 获取远端的用户和密码
    /**
     * 705013246@qq.com
     *
     * */
    private final String USER_NAME = "705013246@qq.com";
    private final String PASS_WORD = "";

    // 克隆和拉取git的方式读取文件
    public List<String> getGitDataFilePath() throws Exception {
        File localPath = new File(LOCAL_PATH);
        String remoteUrl = GIT_PATH;
        String branchName =GIT_BRANCH; // 或者其他分支名称
        String folderPath = MARK_DOWN_PATH; // data文件夹的路径
        List<String> markDownFilePathList = new ArrayList<>();

        Repository repository;
        if (localPath.exists()) {
            repository = openLocalRepository(localPath);
            pullLatestChanges(repository);
        } else {
            repository = cloneRepository(localPath, remoteUrl);
        }

        try (Git git = new Git(repository)) {

            Iterable<RevCommit> commits = git.log().add(repository.resolve(branchName)).call();
            RevCommit commit = commits.iterator().next();
            try (RevWalk revWalk = new RevWalk(repository)) {
                RevTree tree = revWalk.parseTree(commit.getTree());
                try (TreeWalk treeWalk = new TreeWalk(repository)) {
                    treeWalk.addTree(tree);
                    treeWalk.setRecursive(true);
                    while (treeWalk.next()) {
                        if (treeWalk.getPathString().startsWith(folderPath) && treeWalk.getPathString().endsWith(".md")) {
                            System.out.println("Found markdown file: " + treeWalk.getPathString());
                            // 这里可以根据需要进行具体的处理，比如读取文件内容等
                            markDownFilePathList.add(treeWalk.getPathString());
                        }
                    }
                }
            }
        } catch (IOException | GitAPIException e) {
            e.printStackTrace();
        }
        return markDownFilePathList;
    }

    /**
     * @param searchKey 检索关键字
     * @param path markdown文本路径
     * @desc 通过关键字和路径找到指定markdown文件是否内容包含关键字
     * */
    public Boolean isContainSearchKeyForContent(String searchKey,String path) {
        Boolean containFlag = false;
        String content ="";
        try {
            content =  findMarkDownBypathNoWithImage(path);
        }catch (Exception e) {
            System.out.println("获取markdown文本失败:"+e.getMessage());
        }
        if (content.contains(searchKey)) {
            containFlag = true;
        }
        return containFlag;
    }

    public List<String> findGitMarkDown() throws Exception {
        List<String> result = new ArrayList<>();
        String remoteUrl = "https://github.com/user/repo.git";
        String remoteBranch = "master";
        String filePath = "path/to/file.txt";
        // 1. 创建一个临时目录作为 Git 存储库的位置
        Path tempDir = Files.createTempDirectory("temp-git");
        try {

            Repository repo = new RepositoryBuilder()
                .setWorkTree(tempDir.toFile())
                .build();

            // 2. 创建 Transport 和 Git 对象
            try (Transport transport = Transport.open(repo, GIT_PATH)) {
                transport.setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER_NAME, PASS_WORD));

                try (Git git = new Git(repo);
                    RevWalk revWalk = new RevWalk(repo)) {

                    // 3. 获取远程分支的 commit
                    Ref ref = git.fetch()
                        .setRemote(GIT_PATH)
                        .setRefSpecs(new RefSpec("origin/master:" + GIT_BRANCH))
                        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER_NAME, PASS_WORD))
                        .call()
                        .getAdvertisedRef(GIT_BRANCH);

                    RevCommit commit = revWalk.parseCommit(ref.getObjectId());

                    // 4. 使用 TreeWalk 遍历文件
                    try (TreeWalk treeWalk = new TreeWalk(repo)) {
                        treeWalk.addTree(commit.getTree());
                        treeWalk.setRecursive(true);
//                        treeWalk.setFilter(PathFilter.create(filePath));

                        if (treeWalk.next()) {
                            System.out.println(treeWalk.getPathString());
//                            // 5. 读取文件内容
//                            byte[] fileContent = repo.open(treeWalk.getObjectId(0))
//                                .getBytes();
//
//                            String content = new String(fileContent);
//                            System.out.println(content);
                        } else {
                            System.out.println("File not found");
                        }
                    }
                }
            }
        } finally {
            // 6. 清除临时目录
            Files.deleteIfExists(tempDir);
        }

        return result;
    }


    public List<String> getGitDataFileContent(List<String> filePathList) throws Exception {
        List<String> fileContentList = new ArrayList<>();
        String localPath = LOCAL_PATH;
        for (String filePath:filePathList) {
            if (filePath.endsWith(".md")) {
                File markdownFile = new File(localPath, filePath);
                try (Scanner scanner = new Scanner(markdownFile)) {
                    StringBuilder contentBuilder = new StringBuilder();
                    while (scanner.hasNextLine()) {
                        contentBuilder.append(scanner.nextLine()).append("\n");
                    }
                    String markdownContent = contentBuilder.toString();
                    fileContentList.add(markdownContent);
                    // 在这里得到了具体的markdown文件内容
                    System.out.println("Markdown file content:\n" + markdownContent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileContentList;
    }

    public String findMarkDownBypathWithImage(String filePath) throws Exception{
        String localPath = LOCAL_PATH;
        String markDownContent = "";
        if (filePath.endsWith(".md")) {
            File markdownFile = new File(localPath, filePath);
            try (Scanner scanner = new Scanner(markdownFile)) {
                StringBuilder contentBuilder = new StringBuilder();
                while (scanner.hasNextLine()) {
                    contentBuilder.append(scanner.nextLine()).append("\n");
                }
                String markdownContent = contentBuilder.toString();
                markDownContent = loadImages(markdownContent,filePath);
                // 在这里得到了具体的markdown文件内容
                System.out.println("Markdown file content:\n" + markdownContent);
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }
        }
        return markDownContent;
    }

    public String findMarkDownBypathNoWithImage(String filePath) throws Exception{
        String localPath = LOCAL_PATH;
        String markDownContent = "";
        if (filePath.endsWith(".md")) {
            File markdownFile = new File(localPath, filePath);
            try (Scanner scanner = new Scanner(markdownFile)) {
                StringBuilder contentBuilder = new StringBuilder();
                while (scanner.hasNextLine()) {
                    contentBuilder.append(scanner.nextLine()).append("\n");
                }
                markDownContent = contentBuilder.toString();
                System.out.println("Markdown file content:\n" + markDownContent);
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }
        }
        return markDownContent;
    }

    // 克隆git
    private Repository cloneRepository(File localPath, String remoteUrl) throws GitAPIException {
        System.out.println("Cloning repository...");
        Git git = Git.cloneRepository()
            .setURI(remoteUrl)
            .setDirectory(localPath)
            .call();
        return git.getRepository();
    }
    // 打开本地git项目
    private Repository openLocalRepository(File localPath) throws IOException {
        System.out.println("Opening existing repository...");
        Git git = Git.open(localPath);
        return git.getRepository();
    }

    // 打开远端git项目
    private Repository openRepository(String repositoryPath) throws IOException {
        RepositoryBuilder builder = new RepositoryBuilder();
        return builder.setGitDir(new File(repositoryPath))
                .readEnvironment()
                .findGitDir()
                .build();
    }

    //拉取git最新代码
    private void pullLatestChanges(Repository repository) throws GitAPIException {
        System.out.println("Pulling latest changes...");
        Git git = new Git(repository);
        PullCommand pull = git.pull().setTimeout(30);
        pull.call();
    }
    // 加载markdown的图片
    public static String loadImages(String markdownContent) {
        Pattern pattern = Pattern.compile(MARKDOWN_IMAGE_PATTERN);
        Matcher matcher = pattern.matcher(markdownContent);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String originalImageTag = matcher.group(0);
            String altText = matcher.group(1);
            String imagePath = matcher.group(2);
            try {
                String imageData = loadImage(imagePath);
                String transformedImageTag = "![Image](" + imageData + ")";
                matcher.appendReplacement(sb, transformedImageTag);
            } catch (IOException e) {
                // 图像加载出错，可以根据实际需求进行处理
                e.printStackTrace();
            }
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static String loadImage(String imagePath) throws IOException {
        File imageFile = new File(imagePath);

        // 读取图像文件的字节数组
        byte[] imageData = FileUtils.readFileToByteArray(imageFile);

        // 将字节数组转换为Base64编码字符串
        String base64ImageData = java.util.Base64.getEncoder().encodeToString(imageData);

        return "data:image/png;base64," + base64ImageData;
    }


    public  String loadImages(String markdownContent, String markdownFilePath) {
        Pattern pattern = Pattern.compile(MARKDOWN_IMAGE_PATTERN);
        Matcher matcher = pattern.matcher(markdownContent);
        String localPath = LOCAL_PATH;
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String originalImageTag = matcher.group(0);
            String altText = matcher.group(1);
            String imagePath = matcher.group(2);
            try {
                String absoluteImagePath = getAbsoluteImagePath(imagePath, markdownFilePath);
                absoluteImagePath = absoluteImagePath.replace("E:\\myGit_workspace\\search_markdown_end",localPath);
                String imageData = loadImage(absoluteImagePath);
                String transformedImageTag = "![Image](" + imageData + ")";
                matcher.appendReplacement(sb, transformedImageTag);
            } catch (IOException e) {
                // 图像加载出错，可以根据实际需求进行处理
                e.printStackTrace();
            }
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static String getAbsoluteImagePath(String imagePath, String markdownFilePath) {
        File markdownFile = new File(markdownFilePath);
        String markdownDirectory = markdownFile.getParent();
        String absoluteImagePath = new File(markdownDirectory, imagePath).getAbsolutePath();
        return absoluteImagePath;
    }

}
